<template>
    <div class="box">
        <div class="header">
            <input type="text" placeholder="请输入内容" v-model="content">
            <button @click="pub">发布</button>
        </div>
        <ul>
            <li v-for="(item, index) in comments" :key="item.id">
                <span>{{ item.content }}</span>
                <div>
                    <span class="del" @click="delByIndex(index)">删除</span>
                    <span class="del" @click="delById(item.id)">删除</span>
                    <span class="del" @click="delByFilter(item.id)">删除</span>
                </div>
            </li>
        </ul>
    </div>
</template>

<script setup>
import { ref } from 'vue'
const content = ref('')
const comments = ref([])


// 删除(过滤filter:过滤需要删除的内容,留下没被过滤的)
// toString()：将数据转化程统一类型---引用数据类型
const delByFilter = (id) => {
    let index = comments.value.findIndex(item => item.id.toString() === id.toString())
    if (confirm(`确认删除${comments.value[index].content}吗`)) {
        // 数组的filter过滤方法会返回新数组
        let results = comments.value.filter(item => id.toString() !== item.id.toString())
        comments.value = results
    }
}

// 删除(通过id找下标)
// toString()：将数据转化程统一类型---引用数据类型
const delById = (id) => {
    // 通过id找到当前项所在数组中的下标
    let index = comments.value.findIndex(item => item.id.toString() === id.toString())
    if (confirm(`确认删除${comments.value[index].content}吗`)) {
        // splice会改变原数组
        comments.value.splice(index, 1)
    }
}

// 删除(index下标方法)
const delByIndex = (index) => {
    if (confirm(`确认删除${comments.value[index].content}吗`)) {
        // splice会改变原数组
        comments.value.splice(index, 1)
    }
}

// 发布
const pub = () => {
    if (content.value.trim() === '') {
        return
    }
    comments.value.push({ id: Date.now(), content: content.value })
    // 清空输入框
    content.value = ''
}

</script>

<style scoped>
* {
    margin: 0;
    padding: 0;
}
.box {
    width: 300px;
    margin: 50px auto;
}

.box .header {
    display: flex;
}

button {
    flex-grow: 1;
}



ul li {
    display: flex;
    justify-content: space-between;
}

ul li .del {
    color: blue;
    cursor: pointer;
    padding: 0 2px;
}
</style>